﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ZhimeiSoft.Framework.Client.Base;
using ZhimeiSoft.CharmManager.DOL;
using ZhimeiSoft.Framework.Client.Utils;
using ZhimeiSoft.CharmManager.Client.Manager;
using ZhimeiSoft.CharmManager.Client.Interface;

namespace ZhimeiSoft.CharmManager.Client.Forms
{
    public partial class frmReservationCustomFinished : FormBase
    {
        private readonly string codeNameEmpty = "-";
        //当前预约项目的信息
        private DataRow drCurrReservationServiceItemDetail = null;
        /// <summary>
        /// 预约控制类
        /// </summary>
        private ReservationCtrl reservationCtrl = new ReservationCtrl();
        /// <summary>
        /// 当前服务项目
        /// </summary>
        private DBEntityCustomerServiceItem customServiceItem;
        //当前预约信息
        private DBEntityReservation curr_reservationInfo = null;
        private DataSet dsEmployee = new DataSet();
        private DataSet dsNextReservation = new DataSet();
        //预约项目
        private DataSet dsResverationServiceItem = new DataSet();

        private DBEntityCustomInfo customInfo = new DBEntityCustomInfo();
        /// <summary>
        /// 员工ID 和显示MAP
        /// </summary>
        private SortedList<int, string> srotEmployeeName = new SortedList<int, string>();
        //是否生成预约记录
        private bool bNextReservation = false;

        public frmReservationCustomFinished(DBEntityReservation reservationInfo, DataRow drReservationDetail, bool onlyDisplay)
        {
            InitializeComponent();
            drCurrReservationServiceItemDetail = drReservationDetail;
            this.curr_reservationInfo = reservationInfo;
            btnSave.Enabled = !onlyDisplay;
        }

        private void frmReservationCustomFinished_Shown(object sender, EventArgs e)
        {
            string error = string.Empty;
            customServiceItem = new DBEntityCustomerServiceItem(drCurrReservationServiceItemDetail);

            //查询下次预约
            txtSName.Text = drCurrReservationServiceItemDetail[DBEntityServiceItem.FieldName.SNAME].ToString();
            txtNextSName.Text = txtSName.Text;
            txtCServiceEndTime.Text = Convert.ToDateTime(drCurrReservationServiceItemDetail[DBEntityCustomerServiceItem.FieldName.CSERVICEENDTIME]).ToLongDateString();
            txtCBuyTime.Text = Convert.ToDateTime(drCurrReservationServiceItemDetail[DBEntityCustomerServiceItem.FieldName.CBUYTIME]).ToLongDateString();
            txtCServiceStartTime.Text = Convert.ToDateTime(drCurrReservationServiceItemDetail[DBEntityCustomerServiceItem.FieldName.CSERVICESTARTTIME]).ToLongDateString();
            txtRemainCount.Text = drCurrReservationServiceItemDetail[DBEntityCustomerServiceItem.FieldName.CREMAINCOUNT].ToString();
            if (drCurrReservationServiceItemDetail.Table.Columns.IndexOf(DBEntityCustomerServiceItemConsume.FieldName.CMINUSCOUNT) == -1)
            {
                //增加扣减次数字段
                drCurrReservationServiceItemDetail.Table.Columns.Add(new DataColumn(DBEntityCustomerServiceItemConsume.FieldName.CMINUSCOUNT, typeof(Int32)));
            }
            txtCMinusCount.Text = (drCurrReservationServiceItemDetail[DBEntityCustomerServiceItemConsume.FieldName.CMINUSCOUNT] == System.DBNull.Value) ? "1" : drCurrReservationServiceItemDetail[DBEntityCustomerServiceItemConsume.FieldName.CMINUSCOUNT].ToString();
            try
            {
                //预约下一次到店时间
                DateTime reservationNextDatetime = getNextResverationDate(curr_reservationInfo.RESERVATIONTIME, Convert.ToInt16(drCurrReservationServiceItemDetail[DBEntityCustomerServiceItem.FieldName.CUSTOMERSERVICEITEMID]));
                txtResverationDate.Text = reservationNextDatetime.ToLongDateString();
                initEmployeeCbx(Convert.ToInt32(drCurrReservationServiceItemDetail[DBEntityEmployee.FieldName.EMPLOYEEID]));//初始化员工
                memoEdit1.Text = drCurrReservationServiceItemDetail[DBEntityCustomerServiceItemConsume.FieldName.CMEMO].ToString();

                bNextReservation = false;
                if ((Convert.ToInt32(txtRemainCount.Text) - 1) > 0)
                {
                    //如果本次即将扣减完预约项目那么就不会产生下次预约了 >0 表明换可以继续预约
                    bNextReservation = true;
                    //装载下一次的预约记录
                    reservationNext(reservationNextDatetime.Year, reservationNextDatetime.Month, reservationNextDatetime.Day,
                        curr_reservationInfo.CUSTOMERID);
                }
                else
                {
                    groupPanReservation.Enabled = false;
                }

                int iCount = Convert.ToInt16(txtRemainCount.Text) - Convert.ToInt16(txtCMinusCount.Text);
                if (iCount <= 3)
                {
                    labRemind.Text = "该服务项目剩余：" + iCount.ToString() + "次";
                    labRemind.ForeColor = Color.Red;
                    labRemind.Visible = true;
                }
                DataSet dsCustomInfo = new DataSet();
                if (!BussinessProxyManager.Instance.QueryCustomerID(this.curr_reservationInfo.CUSTOMERID, out dsCustomInfo, out error))
                {
                    MsgBox.MsgInfo("获取用户信息错误：" + error);
                    return;
                }
                customInfo = new DBEntityCustomInfo(dsCustomInfo.Tables[0].Rows[0]);
            }
            catch (Exception ex)
            {
                MsgBox.MsgInfo(ex.Message);
                this.Close();
            }
        }
        /// <summary>
        /// 下一次的预约
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <param name="day"></param>
        /// <param name="customid"></param>
        private void reservationNext(int year, int month, int day, int customid)
        {
            string error = string.Empty;
            if (!BussinessProxyManager.Instance.QueryReservationCustom(year, month, day, customid, out dsNextReservation, out error))
            {
                MsgBox.MsgInfo(error);
                return;
            }
            initNextReservation(dsNextReservation);
        }
        /// <summary>
        /// 初始化下次预约
        /// </summary>
        /// <param name="dsReservation"></param>
        private void initNextReservation(DataSet dsReservation)
        {
            string error = string.Empty;
            dateInputReservation.Value = Convert.ToDateTime(txtResverationDate.Text);
            cbxState.SelectedItem = cbxItemC0N;
            //预约ID
            int tmpReservationID = -1;
            if (dsReservation.Tables[0].Rows.Count > 0)
            {
                //有预约记录进行界面装载
                hourTimeSimpleControl.CurrDateTime = Convert.ToDateTime(dsReservation.Tables[0].Rows[0][DBEntityReservation.FieldName.RESERVATIONTIME]);
                dateInputReservation.Value = Convert.ToDateTime(dsReservation.Tables[0].Rows[0][DBEntityReservation.FieldName.RESERVATIONTIME]);
                tmpReservationID = Convert.ToInt32(dsReservation.Tables[0].Rows[0][DBEntityReservation.FieldName.RESERVATIONID]);
            }
            else
            {
                //没有预约记录那么就取下次护理日期 + 上次预约的时间
                DateTime tmpDate = Convert.ToDateTime(txtResverationDate.Text).Date;
                hourTimeSimpleControl.CurrDateTime = new DateTime(tmpDate.Year, tmpDate.Month, tmpDate.Day, curr_reservationInfo.RESERVATIONTIME.Hour,
                curr_reservationInfo.RESERVATIONTIME.Minute, curr_reservationInfo.RESERVATIONTIME.Second);
                hourTimeSimpleControl.CurrDateTime = curr_reservationInfo.RESERVATIONTIME;
            }
            
            if (!BussinessProxyManager.Instance.QueryReservationServiceItem(tmpReservationID, out dsResverationServiceItem, out error))
            {
                MsgBox.MsgInfo("初始化预约项目错误：" + error);
                return;
            }
            DataSet dsServiceItem = new DataSet();
            string filter = DBEntityCustomerServiceItem.FieldName.SERVICEITEMID + " = " + drCurrReservationServiceItemDetail[DBEntityCustomerServiceItem.FieldName.SERVICEITEMID].ToString();
            //装载服务项目
            BussinessProxyManager.Instance.QueryServiceItem(filter, out dsServiceItem, out error);
            DBEntityServiceItem serviceItem =  new DBEntityServiceItem(dsServiceItem.Tables[0].Rows[0]);
            DataRow drReservationDetail = null;
            DBEntityCustomerServiceItem customServiceItem = new DBEntityCustomerServiceItem(drCurrReservationServiceItemDetail);
            DataRow[] drReservationRows = dsResverationServiceItem.Tables[0].Select(DBEntityCustomerServiceItem.FieldName.CUSTOMERSERVICEITEMID + " = " + customServiceItem.CUSTOMERSERVICEITEMID.ToString(), "", DataViewRowState.CurrentRows);
            if (drReservationRows.Length == 0)
            {
                //新增预约项目明细
                reservationCtrl.addReservationDetail(dsResverationServiceItem.Tables[0], serviceItem, customServiceItem, ref drReservationDetail);
                drReservationDetail[DBEntityReservationServiceItem.FieldName.EMPLOYEEID] = drCurrReservationServiceItemDetail[DBEntityReservationServiceItem.FieldName.EMPLOYEEID];
            }
            gdServiceItem.DataSource = dsResverationServiceItem.Tables[0];
        }
        /// <summary>
        /// 获取下次预约护理时间
        /// </summary>
        /// <returns></returns>
        private DateTime getNextResverationDate(DateTime dtNowTime, int customerServiceItemID)
        {
            int iday = 0;
            string error = string.Empty;
            if (!BussinessProxyManager.Instance.ComputerNextReservation(customerServiceItemID, out iday, out error))
            {
                throw new Exception(error);
            }
            dtNowTime = dtNowTime.AddDays(iday);
            return dtNowTime;
        }
        /// <summary>
        /// 初始化员工
        /// </summary>
        /// <param name="employeeID"></param>
        private void initEmployeeCbx(int employeeID)
        {
            string error = string.Empty;
            if (!BussinessProxyManager.Instance.QueryEmployeeState(DBEntityEmployee.ENUM_ESTATE.F0E, out dsEmployee, out error))
            {
                MsgBox.MsgInfo(error);
                return;
            }
            string selectItemTxt = string.Empty;
            
            cbxEmployee.BeginUpdate();
            try
            {
                cbxEmployee.Items.Clear();
                srotEmployeeName.Clear();
                foreach (DataRow drEmployee in dsEmployee.Tables[0].Rows)
                {
                    string empName = drEmployee[DBEntityEmployee.FieldName.ECODE].ToString() + codeNameEmpty + drEmployee[DBEntityEmployee.FieldName.ENAME].ToString();
                    cbxEmployee.Items.Add(empName);
                    repositoryItemComboBoxEmployeeName.Items.Add(drEmployee[DBEntityEmployee.FieldName.ENAME].ToString());
                    srotEmployeeName.Add(Convert.ToInt32(drEmployee[DBEntityEmployee.FieldName.EMPLOYEEID]), drEmployee[DBEntityEmployee.FieldName.ENAME].ToString());
                    if (employeeID == Convert.ToInt32(drEmployee[DBEntityEmployee.FieldName.EMPLOYEEID]))
                    {
                        selectItemTxt = drEmployee[DBEntityEmployee.FieldName.ECODE].ToString() + codeNameEmpty + drEmployee[DBEntityEmployee.FieldName.ENAME].ToString();
                    }
                }
                int idx = cbxEmployee.Items.IndexOf(selectItemTxt);
                if (idx >= 0)
                {
                    cbxEmployee.SelectedIndex = idx;
                }
            }
            finally
            {
                cbxEmployee.EndUpdate();
            }
        }
        /// <summary>
        /// 保存预约完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (MsgBox.MsgQue("确定本次这个项目服务完成吗？") == false)
            {
                return;
            }
            string error = string.Empty;
            if (!checkedInput(out error))
            {
                MsgBox.MsgInfo(error);
                return;
            }
            string empName = cbxEmployee.SelectedItem.ToString(); //drEmployee[DBEntityEmployee.FieldName.ECODE].ToString() + codeNameEmpty + drEmployee[DBEntityEmployee.FieldName.ENAME].ToString();
            string[] empNameArr = empName.Split('-');
            string empCode = string.Empty;
            empName = string.Empty;
            for (int i = 0; i < empNameArr.Length; i++)
            {
                if (i == 0)
                {
                    empCode = empNameArr[i];
                }
                else
                {
                    empName += ((empName == "")?"":"-") + empNameArr[i];
                }
            }
            string filter = DBEntityEmployee.FieldName.ECODE + " = '" + empCode + "' AND " + DBEntityEmployee.FieldName.ENAME + " = '" + empName + "'";
            int employeeID = reservationCtrl.getEmployeeID(dsEmployee.Tables[0], filter);
            
            //保存消费数据
            if (!BussinessProxyManager.Instance.CompleteCustomServiceItem(Convert.ToInt16(drCurrReservationServiceItemDetail[DBEntityReservationServiceItem.FieldName.CUSTOMERSERVICEITEMID]),
                Convert.ToInt16(txtCMinusCount.Text), DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString(), "" + memoEdit1.Text, employeeID.ToString(), customServiceItem, 
                curr_reservationInfo.RESERVATIONID, out error))
            {
                MsgBox.MsgInfo("保存服务数据失败：" + error);
                return;
            }
            if (!BussinessProxyManager.Instance.UpdateReservationCustomServiceItemState(curr_reservationInfo.RESERVATIONID, Convert.ToInt16(drCurrReservationServiceItemDetail[DBEntityReservationServiceItem.FieldName.CUSTOMERSERVICEITEMID]),
                employeeID, DBEntityReservationServiceItem.ENUM_RESERVATIONSTATE.C0A, out error))
            {
                MsgBox.MsgInfo("保存服务项目数据错误：" + error);
                return;
            }

            if (!bNextReservation)
            {
                //无需预约
                return;
            }
            //预约明细记录 dsNextReservation.Tables[1]

            DBEntityReservation reservationInfo = new DBEntityReservation();

            if (dsNextReservation.Tables[0].Rows.Count != 0)
            {
                reservationInfo = new DBEntityReservation(dsNextReservation.Tables[0].Rows[0]);
            }
            else
            {
                reservationInfo.RESERVATIONID = -1;
                reservationInfo.CUSTOMERID = this.curr_reservationInfo.CUSTOMERID;
                reservationInfo.RESERVATIONTIME = new DateTime(getReservationDateTime().Ticks);
                //预约到店时间就是操作时间
                reservationInfo.RWORKSTARTTIME = reservationInfo.RESERVATIONTIME;
                //操作完成时间
                reservationInfo.RWORKENDTIME = new DateTime(reservationInfo.RESERVATIONTIME.Ticks);
                
            }
            DataRow[] drReservationServiceItem = dsResverationServiceItem.Tables[0].Select("", "", DataViewRowState.CurrentRows);
            foreach (DataRow dr in drReservationServiceItem)
            {
                dr[DBEntityReservation.FieldName.RESERVATIONID] = reservationInfo.RESERVATIONID;
            }
            reservationInfo.RMEMO = txtRMemo.Text.Trim();
            reservationInfo.RSTATE = DBEntityReservation.ENUM_RSTATE.ChineseStrToEnumStr(cbxState.SelectedItem.ToString());
            reservationInfo.RWORKENDTIME = reservationInfo.RWORKENDTIME.AddMinutes(reservationCtrl.getResverationDetailTimeSpan(dsResverationServiceItem.Tables[0]));
            bool bresult = BussinessProxyManager.Instance.UpdateReservation(reservationInfo, dsResverationServiceItem, out error);
            ///刷新提醒
            bresult = BussinessProxyManager.Instance.refershReservationToDoList(reservationInfo, out error);
            if (!bresult)
            {
                MsgBox.MsgInfo("保存失败错误信息为：" + error);
                return;
            }
            MsgBox.MsgInfo("当前项目已经预约完成。");
            this.DialogResult = DialogResult.OK;
        }

        private bool checkedInput(out string error)
        {
            error = string.Empty;
            if(txtCMinusCount.Text.Trim().Equals(string.Empty)){
                error = "请设置扣减次数。";
                SetErrorControl(txtCMinusCount, error);
                return false;
            }
            int iMinusCount = 0;
            
            if(!int.TryParse(txtCMinusCount.Text.Trim(), out iMinusCount)){
                error = "请设置正确的扣减次数。";
                SetErrorControl(txtCMinusCount, error);
                return false;
            }
            if(cbxEmployee.SelectedItem == null){
                error = "请选择服务美容师。";
                SetErrorControl(cbxEmployee, error);
                return false;
            }
            return true;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void dateInputReservation_ValueChanged(object sender, EventArgs e)
        {
            //切换预约时间
        }

        private void repositoryItemComboBoxEmployeeName_EditValueChanged(object sender, EventArgs e)
        {
            repositoryItemComboBoxEmployeeName.BeginUpdate();
            try
            {
                DataRow drRow = gvServiceItem.GetDataRow(gvServiceItem.FocusedRowHandle);
                string strValue = ((DevExpress.XtraEditors.ComboBoxEdit)sender).SelectedItem.ToString();
                DataRow[] drEmployees = dsEmployee.Tables[0].Select(DBEntityEmployee.FieldName.ENAME + " = '" + strValue + "'");
                if (drEmployees.Length != 0)
                {
                    drRow[DBEntityEmployee.FieldName.EMPLOYEEID] = drEmployees[0][DBEntityEmployee.FieldName.EMPLOYEEID];
                }
            }
            finally
            {
                repositoryItemComboBoxEmployeeName.EndUpdate();
            }
        }

        private void gvServiceItem_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.RowHandle < 0)
            {
                return;
            }
            if (e.Column.FieldName.Equals(DBEntityEmployee.FieldName.EMPLOYEEID))
            {
                if (e.CellValue == null || e.CellValue.ToString() == string.Empty)
                    return;
                
                string displayText = srotEmployeeName[Convert.ToInt32(e.CellValue)].ToString();
                if (displayText.Equals(string.Empty))
                    return;
                e.DisplayText = displayText;
            }
        }

        private DateTime getReservationDateTime()
        {
            DateTime dt = new DateTime(dateInputReservation.Value.Year, dateInputReservation.Value.Month, dateInputReservation.Value.Day,
                hourTimeSimpleControl.CurrDateTime.Hour, hourTimeSimpleControl.CurrDateTime.Minute, hourTimeSimpleControl.CurrDateTime.Second);
            return dt;
        }

        private void dateInputReservation_Click(object sender, EventArgs e)
        {
        }

        private void btnQueryReservation_Click(object sender, EventArgs e)
        {
            frmCustomReservationMonth frmCustom = new frmCustomReservationMonth();
            frmCustom.QueryReservation(curr_reservationInfo.RESERVATIONTIME, customInfo);
            frmCustom.ShowDialog();
        }
    }
}
